<template>
  <div>
    <div v-if="!noCount">
      <div class="qup-title-box"><span class="border" /><span>走访问题统计</span></div>
      <el-table
        :key="renderKey"
        :data="[{}]"
        border
        max-height="700"
        :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
        style="width: 100%"
      >
        <el-table-column
          v-for="(item,index) in propTable"
          :key="index"
          show-overflow-tooltip
          prop="todo"
          header-align="center"
          :label="item.belongDutyName"
        >
          <el-table-column
            v-for="(i,key) in item.problemList"
            :key="key"
            header-align="center"
            align="center"
            show-overflow-tooltip
            :label="i.acceptProblemName"
          >
            <template>{{ i.num }}</template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>

    <div class="qup-title-box"><span class="border" /><span>走访问题信息</span></div>
    <div v-if="pageType==='2'" style="padding-bottom:10px">
      <el-button size="mini" type="primary" @click.native="handleEditBatch">一键无需整改</el-button>
      <el-button size="mini" type="primary" @click.native="handleEditItem">撤销无需整改</el-button>
      <el-button size="mini" type="primary" @click.native="handleDelete">删除</el-button>
      <el-button size="mini" type="primary" @click.native="refreshTable()">刷新</el-button>
    </div>
    <div v-if="pageType==='uploadRectifyFile'" style="padding-bottom:10px">
      <el-button size="mini" type="primary" @click.native="handleEdit">编辑</el-button>
    </div>
    <div v-if="!noBtns&&!isDetail&&pageType!=='2'&&pageType!=='uploadRectifyFile'" style="padding-bottom:10px">
      <el-button v-if="!noCount" size="mini" type="primary" @click.native="handleAdd">新增</el-button>
      <el-button size="mini" type="primary" @click.native="handleEdit">编辑</el-button>
      <el-button v-if="!noCount" size="mini" type="primary" @click.native="handleDelete">删除</el-button>
      <!-- <el-button size="mini" :loading="saveLoading" type="primary" @click.native="handleTableSave">保存</el-button> -->
      <el-button size="mini" type="primary" @click.native="refreshTable()">刷新</el-button>
    </div>
    <el-table
      v-loading="dataLoading"
      :data="tableProblmeData"
      border
      max-height="300"
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      style="width: 100%;margin-bottom:60px"
      highlight-current-row
      @selection-change="selectionChangeHandle"
    >
      <el-table-column type="index" width="50" />
      <el-table-column type="selection" width="55" />
      <el-table-column show-overflow-tooltip prop="floorCode" label="走访楼层">
        <template slot-scope="scope">
          <c-dict-select v-model="scope.row.floorCode" disabled dict-type-code="FLOOR" />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="areaId" label="走访区域">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.areaId"
            placeholder="请选择"
            style="width: 100%"
            disabled
          >
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.areaName"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="acceptProblemId" label="问题分类">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.acceptProblemId"
            disabled
          >
            <el-option
              v-for="item in acceptProblemList"
              :key="item.id"
              :label="item.problemClass"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column min-width="130" show-overflow-tooltip prop="problemNotes" label="问题描述" />
      <el-table-column label="整改前">
        <template slot-scope="scope">
          <import-img
            :photo-list="scope.row.fileList1"
            readonly
            file-type="整改前"
            :config-attachment-id="configIdBefore"
          />
        </template>
      </el-table-column>
      <el-table-column label="整改后">
        <template slot-scope="scope">
          <import-img
            :photo-list="scope.row.fileList2"
            file-type="整改后"
            readonly
            :other-param="scope.$index"
            :config-attachment-id="configIdAfter"
            @upload-success="changeTableStatus"
            @remove="changeTableStatus"
          />
        </template>
      </el-table-column>
      <el-table-column width="120" show-overflow-tooltip prop="status" label="整改情况">
        <template slot-scope="scope">
          <c-dict-select v-model="scope.row.status" disabled dict-type-code="RECTIFICATION_SITUATION" />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="specialNo" label="特殊流程编号" />
    </el-table>
    <el-dialog
      v-if="dlgVisible"
      ref="refDlg"
      :visible.sync="dlgVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closeDialog"
      width="600px"
      :title="editForm.id?'编辑':'新增'"
      @close="closeDialog"
    >
      <el-form ref="refForm" :rules="editRules" :model="editForm" size="mini" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="走访楼层:" prop="floorCode">
              <c-dict-select v-model="editForm.floorCode " :disabled="!!editForm.id" dict-type-code="FLOOR" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="走访区域:" prop="areaId">
              <el-select
                v-model="editForm.areaId"
                :disabled="!!editForm.id"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in areaList"
                  :key="item.id"
                  :label="item.areaName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="问题分类:" prop="acceptProblemId">
              <el-select
                v-model="editForm.acceptProblemId"
                :disabled="!!editForm.id"
              >
                <el-option
                  v-for="item in acceptProblemList"
                  :key="item.id"
                  :label="item.problemClass"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="问题描述:" prop="problemNotes">
              <el-input v-model="editForm.problemNotes" :disabled="!!editForm.id" size="mini" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="整改前:" prop="fileList1">
              <import-img
                :photo-list="editForm.fileList1"
                file-type="整改前"
                :readonly="!!editForm.id"
                :config-attachment-id="configIdBefore"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="整改后:" prop="">
              <import-img
                :photo-list="editForm.fileList2"
                file-type="整改后"
                :config-attachment-id="configIdAfter"
                @upload-success="changeStatus"
                @remove="changeStatus"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="整改情况:" prop="status">
              <span v-if="pageType==='uploadRectifyFile'">
                <el-select
                  v-model="editForm.status"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.dictCode"
                    :disabled="item.dictCode!=='C'&&item.dictCode!=='D'"
                    :label="item.dictName"
                    :value="item.dictCode"
                  />
                </el-select>
              </span>
              <span v-else>
                <el-select
                  v-model="editForm.status"
                  placeholder="请选择"
                  :disabled="schedule!=='B'||$route.name==='PatrolRectify'"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.dictCode"
                    :disabled="item.dictCode!=='C'&&item.dictCode!=='D'"
                    :label="item.dictName"
                    :value="item.dictCode"
                  />
                </el-select>
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :rules="[{ required: editForm.status==='C', message: '请填写特殊流程编号', trigger: 'change' }]" label="特殊流程编号:" prop="specialNo">
              <el-input v-model="editForm.specialNo" size="mini" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button :loading="saveLoading" size="mini" type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import importImg from '@/components/importImg/miniUpload'
import { getAreaList } from '@/api/common'
import { getDictByPatchType } from '@/api/dataDict'
import { deepClone } from '@/utils'
import { queryPatrolQuestionList, queryDutyListTree, savePatrolQuestionList, deletePatrolQuestion, queryProblemClassList } from '@/api/marketService/dailyPatrol'
export default {
  name: 'PatrolQuestion',
  components: { importImg },
  props: {
    patrolId: {
      type: String,
      default: ''
    },
    isDetail: {
      type: [Number, Boolean],
      default: false
    },
    picConfigId: {
      type: String,
      default: ''
    },
    configIdBefore: {
      type: String,
      default: ''
    },
    schedule: {
      type: String,
      default: ''
    },
    model: {
      type: String,
      default: ''
    },
    configIdAfter: {
      type: String,
      default: ''
    },
    noCount: {
      type: Boolean,
      default: false
    },
    noBtns: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      renderKey: false,
      dataLoading: false,
      dlgVisible: false,
      pageType: '',
      propTable: [],
      editForm: {},
      acceptProblemList: [],
      tableSelected: [],
      saveLoading: false,
      tableProblmeData: [],
      statusOptions: [],
      areaList: [],
      editRules: {
        floorCode: [{ required: true, message: '请选择', trigger: 'change' }],
        areaId: [{ required: true, message: '请选择', trigger: 'change' }],
        acceptProblemId: [{ required: true, message: '请选择', trigger: 'change' }],
        fileList1: [{ required: true, type: 'array', message: '请上传', trigger: 'change' }]
      }
    }
  },
  watch: {
    patrolId: {
      handler(v) {
        if (!v) return
        this.handelQueryDutyList(v)
        this.refreshTable()
      },
      deep: true,
      immediate: true
    }
  },
  async created() {
    const { type } = this.$route.query
    this.pageType = type
    queryProblemClassList().then(res => {
      if (res.success) this.acceptProblemList = res.data.records || []
    })
    getAreaList().then(res => {
      if (res.success) this.areaList = res.data.records || []
    })
    const { RECTIFICATION_SITUATION } = await getDictByPatchType(['RECTIFICATION_SITUATION'])
    this.statusOptions = RECTIFICATION_SITUATION
  },
  methods: {
    handleEditBatch() {

    },
    handleEditItem() {
      if (!this.singleJudge(this.tableSelected, '撤销', true)) {
        return
      }
      if (this.tableSelected[0].status === 'A') {
        this.$message.warning('当前状态已为未整改')
        return
      }
      this.saveLoading = true
      savePatrolQuestionList({ ...this.tableSelected[0], status: 'A' }).then(res => {
        if (res.success) {
          if (this.patrolId) this.refreshTable()
          this.$message.success('保存成功')
        }
        this.saveLoading = false
      }).catch(() => {
        this.saveLoading = false
      })
    },
    getValid(type) { // type为1表示提交，路由的type2代表校验整改状态
      if (type && this.$route.query.type === '2' && this.tableProblmeData.filter(v => v.status === 'A').length) return false
      else return true
    },
    closeDialog() {
      this.dlgVisible = false
      this.editForm = {}
    },
    classify(dataList) {
      // 定义一个用来存已经分好类数据的数组
      var arr2 = []
      // 遍历数组
      for (var i = 0; i < dataList.length; i++) {
        // 判断新定义的数组有没有值  没有值则减第一个类给他赋值上去
        if (arr2.length === 0) {
          arr2.push({
            acceptProblemId: dataList[i].acceptProblemId,
            data: [dataList[i]]
          })
        } else { // 第一个完后 后面的有值了 使用findindex()方法进行比较 存在返回下标index 不存在则返回-1
          var index = arr2.findIndex(item => {
            return item.acceptProblemId === dataList[i].acceptProblemId
          })
          // 判断index是否大于0 大于0则在该类的data push进该类别的数据
          if (index >= 0) {
            arr2[index].data.push(dataList[i])
          } else { // 不存在则新建一个对象  push 进arr2 里面 作为第二个类
            arr2.push({
              acceptProblemId: dataList[i].acceptProblemId,
              data: [dataList[i]]
            })
          }
        }
      }
      return arr2
    },
    changeArea() {
      const dataList = this.classify(this.tableProblmeData)
      for (let j = 0; j < this.propTable.length; j++) {
        for (let i = 0; i < this.propTable[j].problemList.length; i++) {
          for (let k = 0; k < dataList.length; k++) {
            if (dataList[k].acceptProblemId === this.propTable[j].problemList[i].acceptProblemId) {
              this.propTable[j].problemList[i].num = dataList[k].data.length
              this.renderKey = !this.renderKey
            }
          }
        }
      }
    },
    changeTableStatus({ imgLength, otherParam }) {
      //  （3）巡检任务进度为【待提交】A，上传整改后的图片时，整改情况默认为【现场已整改】D
      if (this.schedule === 'A') {
        if (imgLength > 0) {
          this.$set(this.tableProblmeData[otherParam], 'status', 'D')
        } else {
          this.$set(this.tableProblmeData[otherParam], 'status', 'A')
        }
      } else {
        this.$set(this.tableProblmeData[otherParam], 'status', 'A')
      }
    },
    changeStatus({ imgLength }) {
      //  （3）巡检任务进度为【待提交】A，上传整改后的图片时，整改情况默认为【现场已整改】D
      //  （3）巡检任务进度为【待审核】B，上传整改后的图片时，整改情况默认为【现场已整改】D
      // 问题整改页面上传整改后图片状态变更为【已整改】B
      if (imgLength > 0 && this.$route.name === 'PatrolRectify') {
        this.$set(this.editForm, 'status', 'B')
      } else if (imgLength > 0 && this.$route.name === 'DailyPatrolEdit') {
        this.$set(this.editForm, 'status', 'D')
      } else {
        this.$set(this.editForm, 'status', 'A')
      }
      // } else {
      //   this.$set(this.editForm, 'status', 'A')
      // }
    },
    handleDelete() {
      if (!this.singleJudge(this.tableSelected, '删除', true)) return
      if (!this.tableSelected[0].id) {
        const keyIndex = this.tableProblmeData.findIndex(v => v.addFlag === this.tableSelected[0].addFlag)
        this.tableProblmeData.splice(keyIndex, 1)
      } else {
        deletePatrolQuestion(this.tableSelected[0].id).then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.refreshTable()
          }
        })
      }
    },
    handleEdit() {
      if (!this.singleJudge(this.tableSelected, '编辑', true)) {
        return
      }
      // const KeyIndex = this.tableProblmeData.findIndex(v => (v.id && this.tableSelected[0].id && v.id === this.tableSelected[0].id) || (v.addFlag && this.tableSelected[0].addFlag && v.addFlag === this.tableSelected[0].addFlag))
      // this.$set(this.tableProblmeData[KeyIndex], 'isEdit', true)
      this.editForm = deepClone(this.tableSelected[0])
      this.dlgVisible = true
    },
    handleAdd() {
      let item
      if (this.tableProblmeData.length) {
        const { acceptProblemId, areaId, floorCode, patrolId, rectifyId,
          shopAttachmentDTOList } = this.tableProblmeData[this.tableProblmeData.length - 1]
        // const file1 = fileList1.map(v => { return { ...v, modelId: '', id: null } })
        // const file2 = fileList2.map(v => { return { ...v, modelId: '', id: null } })
        item = { addFlag: Math.floor(Math.random() * 0xffffff).toString(16), acceptProblemId, areaId,
          floorCode, patrolId, fileList1: [], fileList2: [], problemNotes: '',
          rectifyId, specialNo: '', status: 'A',
          shopAttachmentDTOList, isEdit: true }
      } else {
        item = {
          addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
          acceptProblemId: '',
          areaId: '',
          floorCode: '',
          id: null,
          patrolId: this.patrolId,
          fileList1: [],
          fileList2: [],
          problemNotes: '',
          rectifyId: '',
          specialNo: '',
          status: 'A',
          shopAttachmentDTOList: [],
          isEdit: true
        }
      }
      this.editForm = item
      this.dlgVisible = true
      // this.tableProblmeData.push(item)
    },
    // 刷新表格
    refreshTable() {
      this.dataLoading = true
      queryPatrolQuestionList(this.patrolId).then(res => {
        if (res.success) {
          res.data.records.map(v => {
            this.$set(v, 'fileList1', (v.shopAttachmentDTOList || []).filter(v => v.configAttachmentId === this.configIdBefore))
            this.$set(v, 'fileList2', (v.shopAttachmentDTOList || []).filter(v => v.configAttachmentId === this.configIdAfter))
          })
          this.tableProblmeData = res.data.records
          this.changeArea()
        }
        this.dataLoading = false
      }).catch(() => {
        this.dataLoading = false
      })
    },
    selectionChangeHandle(rows) {
      this.tableSelected = rows
      if (this.noBtns) this.$emit('select', rows)
    },
    getData() {
      return this.otherFiles.map(v => { return { ...v.response.data, modelId: this.patrolId } })
    },
    handelQueryDutyList() {
      queryDutyListTree('B').then(res => {
        if (res.success) {
          const tempData = res.data
          tempData.forEach(el => {
            this.$set(el, 'patrolId', this.patrolId)
            el.problemList.forEach(i => {
              this.$set(i, 'num', 0)
            })
          })
          this.propTable = tempData
          this.changeArea()
        }
      })
    },
    handleTableSave() {
      if (!this.singleJudge(this.tableSelected, '保存', true)) {
        return
      }
      this.tableSelected[0].shopAttachmentDTOList = [
        ... this.tableSelected[0].fileList1,
        ... this.tableSelected[0].fileList2
      ]
      this.saveLoading = true
      savePatrolQuestionList(this.tableSelected[0]).then(res => {
        if (res.success) {
          this.$message.success('保存成功')
        }
        this.saveLoading = false
      }).catch(() => {
        this.saveLoading = false
      })
    },
    handleSave() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          this.editForm.shopAttachmentDTOList = [
            ... this.editForm.fileList1,
            ... this.editForm.fileList2
          ]
          this.saveLoading = true
          savePatrolQuestionList(this.editForm).then(res => {
            if (res.success) {
              if (this.patrolId) this.refreshTable()
              else {
                const keyindex = this.tableProblmeData.findIndex(v => v.id && v.id === res.data)// 判断原表格是否有此条问题
                keyindex !== -1 ? this.tableProblmeData[keyindex] = { ...this.editForm, id: res.data } : this.tableProblmeData.push({ ...this.editForm, id: res.data })
              }
              // else this.tableProblmeData.push({ ...this.editForm, id: res.data })
              this.closeDialog()
              this.$message.success('保存成功')
            }
            this.saveLoading = false
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    }
  }
}
</script>
